<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-08 14:55:13
 * @LastEditTime: 2020-06-13 12:24:37
 * @LastEditors: Please set LastEditors
 -->
<style scoped>
.headerBtn{
    text-align: left;
    margin: 10px 0;
}
.pageStyle{
    text-align:right
}
.ivu-table-wrapper{
    overflow:visible
}
.pageStyleVm{
    text-align: center
}
table .ivu-poptip-confirm .ivu-poptip-body .ivu-icon{
    left: 11px
}
.position_i{
    position: relative;
    top: -1px;
    margin-right: 5px
}
/* td{
    border-right: 0 !important
} */
.ivu-table-tip{
    overflow: hidden !important;
}
.starlet{
    color: red;
    position: absolute;
    left: -60px;
    font-size: 18px;
    line-height: 38px;
    font-weight: 800;
}
.zIndexStyleBtn{
    position:relative;
    z-index:55
}
/deep/ .ivu-poptip-confirm .ivu-poptip-body .ivu-icon {
    left: 12px;
    top: 22px;
}
</style>

<template>
    <SearchTable
        :columns="columnsData" 
        :data="taskData"
        :total="taskTotal"
        :page="taskCurrentPage" 
        :size="taskItemPage" 
        :change-page="switchineTaskCurrentPage"
        :change-size="switchTaskItemPage"
        showSelectTag
        :disabled="disabledAllBtn"
        :selection.sync="selectedData"
    >
        <template slot="search">
            <Button type="primary" ghost @click="createFlagTask" icon="md-add" :disabled="disabledAllBtn">创建任务</Button>
            <BatchRemove
                    class="zIndexStyleBtn"
                    :dataNum="selectedData.length"
                    @on-ok="deleteManyTask"
                    @on-cancel="cancel"></BatchRemove>
            <!-- <Button type="primary" @click="autoConfigerTask" class="zIndexStyleBtn">自动配置EDR通道</Button> -->
            <!-- <Button type="primary" @click="taskConfigerMess = true"><Icon type="md-settings" :size="16" class="position_i"/>配置管理</Button> -->
        </template>
        <Modal
            v-model="createFlagTaskModal"
            :title="judgePanelType ? '创建任务':'修改任务' "
            ok-text = "确定"
            width=600
            :loading = createFlagTaskModalLoading
            :mask-closable="false"
            
            @on-ok="ok"
            @on-cancel="cancel">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="名称" prop="name">
                    <Input v-model="formValidate.name" placeholder="请输入任务名称" clearable :maxlength="64"></Input>
                </FormItem>
                <!-- <FormItem label="类型" prop="taskMode">
                    <RadioGroup v-model="formValidate.taskMode">
                        <Radio label="preset" :disabled="disabledTepBol">流程任务</Radio>
                        <Radio label="preset" :disabled="disabledTepBol">预设临机任务</Radio>
                    </RadioGroup>
                </FormItem> -->
                <FormItem label="子网" prop="subnets">
                    <Select filterable v-model="formValidate.subnets" placeholder="请选择子网" multiple filterable ref="store">
                        <Option v-for="item in subnetsData" :key="item.id" :value="item.id">名称：{{item.name}}，CIDR:{{item.cidr}}</Option>
                    
                    </Select>
                </FormItem>
                <!-- <FormItem label="指定IP" prop="">
                    <Input  placeholder="指定IP" clearable :maxlength="64"></Input>
                </FormItem> -->
                <FormItem label="协议" prop="protocol">
                    <RadioGroup v-model="formValidate.protocol">
                        <Radio label="tcp"></Radio>
                        <Radio label="udp"></Radio>
                        <Radio label="icmp"></Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem v-model="formValidate.selectedVmData"  label="服务">
                    <span class="starlet">*</span>
                    <input type="hidden" >
                    <Tag v-for="item in formValidate.selectedVmData" :key="item.name" :name="item.id" closable @on-close="handleClose2" color="primary" type='dot' >{{ item.name }}</Tag>
                </FormItem>
                <div style="text-align:right">
                    <Input placeholder="请输入名称" style="width: 210px" v-model="formValidate.vmName" clearable></Input>
                    <Input placeholder="请输入IP" style="width: 210px" v-model="formValidate.vmIP" clearable></Input>
                    <Button type="primary" @click="refreshVmList" style="margin-left:5px">搜索</Button>
                </div>
                <Table ref="" :columns="columnsVmList" :data="dataVmList"  :stripe="showStripe" :show-header="showHeader" :size="tableSize" style="margin-top:5px"></Table>
                <Page :total="vmTotal"   :current="vmCurrentPage" :page-size="vmItemPage" :show-total= true  @on-change="switchineVmCurrentPage" @on-page-size-change="switchVmItemPage" class-name="pageStyleVm"/>
                <FormItem label="属性" >
                    <cusAttribute ref="cusAttribute" @func="getMsgFormSon" v-bind:msgVal="propertiesData"></cusAttribute>
                </FormItem>
                <FormItem label="描述" prop="desc" style="margin-top:10px">
                    <Input v-model="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入内容" clearable :maxlength="200"></Input>
                </FormItem>
            </Form>
        </Modal>
        <Modal
            v-model="taskDeailModal"
            title="任务启动详情"
            width = '80%'
            :mask-closable="false"
            >
            <Table border ref="" :columns="taskDeailColumns" :data="taskDeailData"  :stripe="showStripe" :show-header="showHeader" :size="tableSize" @on-expand="hostDeail"></Table>
        </Modal>
    </SearchTable>
</template>
<script>
import axios from '@/libs/axios1'
import {validateName,taskMixin } from './taskMixin'
// import outbandCaptureCollect from '@/components/configer/outbandCaptureCollect'
export default {
    name:"protocol",
    mixins:[taskMixin],
    data(){
        return{
            configName:'',
            tableHeight:'',
            subnetsData:[],
            taskConfigerMess:false,
            // projectId:"",
            taskTypeTable:'tunnel',
            taskTypeTableTitle:"数据通道",
            selectedData:[],
            // amendTaskId:"",
            columnsData: [],
            taskData: [
                
            ],
            columnsVmList:[
                {
                    type:'radio',
                    type:"expand",
                    width:'30',
                    render: (h, params) => {
                        return h('div',{},[
                            h('Row',{props:{class:'expand-row'}},[
                                h('Col',{props:{span:'8'},style:{width:'50%'}},[
                                    h('span',{props:{class:'expand-key'}},'bridge:  '),
                                    h('span',{props:{class:'expand-value'}},params.row.bridge)
                                ]),
                                h('Col',{props:{span:'8'},style:{width:'50%'}},[
                                    h('span',{props:{class:'expand-key'}},'port:  '),
                                    h('span',{props:{class:'expand-value'}},params.row.port)
                                ]),
                            ]),
                            h('Row',{props:{class:'expand-row'}},[
                                h('Col',{props:{span:'8'},style:{width:'50%'}},[
                                    h('span',{props:{class:'expand-key'}},'creatorName:  '),
                                    h('span',{props:{class:'expand-value'}},params.row.creatorName)
                                ]),
                                h('Col',{props:{span:'8'},style:{width:'50%'}},[
                                    h('span',{props:{class:'expand-key'}},'createTime:  '),
                                    h('span',{props:{class:'expand-value'}},params.row.createTime)
                                ]),
                            ]),
                            // h('Row',{props:{class:'expand-row'},},[
                            //     h('Col',{props:{span:'8'},style:{width:'100%'}},[
                            //         h('span',{props:{class:'expand-key'}},'status:  '),
                            //         h('span',{props:{class:'expand-value'}},params.row.status)
                            //     ]),
                            // ]),
                        ])
                    }
                },
                {
                    title:'名称',
                    key:'name',
                    align:'center'
                },
                {
                    title:'IP',
                    key:'ip',
                    align:'center',
                    // render:(h,params)=>{
                    //     let value = params.row.IP;
                    //     let oIP_ = [];
                    //     $.each(value,(i,item)=>{
                    //         oIP_.push(h("p",{
                    //             color:'#000',
                    //         },item))
                    //     })
                    //     return h("div",oIP_)
                    // }
                },
                {
                    title:'添加',
                    key:'add',
                    align:'center',
                    render:(h,params) =>{
                        let _this = params;
                        return h('Button', {
                            props: {
                                type: 'primary',
                            },
                            on:{
                                
                                 click: (e) => {
                                    if(this.selectedVmDataTable.indexOf(_this.row.id)!=-1){
                                        this.$Message.info("已添加")
                                        return;
                                    }
                                    // alert('-')
                                    this.addVmAfterTable(_this.row)
                                    this.selectedVmDataTable.push(_this.row.id)
                                    this.formValidate.selectedVmData.push({
                                        "name":_this.row.name,
                                        "id":_this.row.id
                                    })
                                },

                                click: (e) => {
                                    this.selectedVmDataTable = [];
                                    this.selectedVmDataTable.push(_this.row.id)
                                    // if(this.selectedVmDataTable.indexOf(_this.row.id)!=-1){
                                    //     this.$Message.info("已添加")
                                    //     return;
                                    // } 
                                    
                                    // alert('-')
                                    this.addVmAfterTable(_this)
                                    this.formValidate.selectedVmData = [];
                                    // this.selectedVmDataTable.push(_this.row.id)
                                    this.formValidate.selectedVmData.push({
                                        "name":_this.row.name,
                                        "id":_this.row.id
                                    })
                                },

                            }
                        }, "+");
                    }
                }
            ],
            dataVmList:[
                
            ],
            selectedVmDataTable:[
                
            ],
            configurationData:[
                
            ],
            createFlagTaskModalLoading:true,
            showBorder: false,
            showStripe: true,
            showHeader: true,
            showIndex: true,
            showCheckbox: false,
            fixedHeader: false,
            tableSize: 'small',
            createFlagTaskModal : false,
            formValidate: {
                name: '',
                subnets: [],
                protocol:'tcp',
                selectedVmData:[
                    
                ],
                desc: '',
                vmName:'',
                vmIP:'',
                taskMode:'preset',
            },
            ruleValidate: {
                name: [
                    { required: true, message: '', trigger: 'blur',validator:validateName }
                ],
                subnets: [
                    { required: true, message: '请选择子网', trigger: 'change',type:'array'},
                ],
                selectedVmData:[
                    {required:true ,message:"请选择服务"}
                ],
                protocol:[
                    {required:true ,message:"请选择协议",trigger: 'change'}
                ],
                taskMode: [
                   { required: true, message: '', trigger: 'blur'}
                ],
            },
            vmCurrentPage:1,
            vmItemPage:10,
            vmTotal:0,
            taskCurrentPage:1,
            taskItemPage:10,
            taskTotal:0,
            judgePanelType:true,//判断是修改还是保存
            workingAreaTaskId:"",//存放修改的任务id

            //查看详情面板
            taskDeailModal:false,
            taskDeailColumns:[
                // {
                    // type:"expand",
                    // width:'30',
                    // render: (h, params) => {
                    //     return h('div',{},[
                    //         h('Row',{props:{class:'expand-row'}},[
                    //             h('Col',{props:{span:'8'},style:{width:'50%'}},[
                    //                 h('span',{props:{class:'expand-key'}},'host:  '),
                    //                 h('span',{props:{class:'expand-value'}},params.row.host)
                    //             ]),
                    //             h('Col',{props:{span:'8'},style:{width:'50%'}},[
                    //                 h('span',{props:{class:'expand-key'}},'hostIP:  '),
                    //                 h('span',{props:{class:'expand-value'}},params.row.hostIp)
                    //             ]),
                    //         ]),
                    //         h('Row',{props:{class:'expand-row'}},[
                    //             h('Col',{props:{span:'8'},style:{width:'100%'}},[
                    //                 h('span',{props:{class:'expand-key'}},'instance_name:  '),
                    //                 h('span',{props:{class:'expand-value'}},params.row.instance)
                    //             ]),
                    //         ]),
                    //         h('Row',{props:{class:'expand-row'},},[
                    //             h('Col',{props:{span:'8'},style:{width:'100%'}},[
                    //                 h('span',{props:{class:'expand-key'}},'osId:  '),
                    //                 h('span',{props:{class:'expand-value'}},params.row.osId)
                    //             ]),
                    //         ]),
                    //     ])
                    // }
                // },
                {
                    title:this.$t('name'),
                    key:'deviceName',
                    align:'center'
                },
                {
                    title:this.$t('Status'),
                    key:'status',
                    align:'center',
                    render:(h,params)=>{
                        return this.renderTaskStatus(h,params.row.status)
                    }
                },
                {
                    title:this.$t('CreateTime'),
                    key:'created',
                    align:'center'
                },
                {
                    title:'协议',
                    key:'protocol',
                    align:'center'
                },
                {
                    title:this.$t('Message'),
                    key:'message',
                    align:'center'
                },
                // {
                //     title:'operation',
                //     key:'-',
                //     align:'center',
                //     render:(h,params)=>{
                //         return h("Button",{
                //             props:{
                //                 type:'primary'
                //             }
                //         },"查看结果")
                //     }
                // }
            ],
            taskDeailData:[],
            setintervalTime:setInterval(() => {
                
            }, 1000),
            // sceneId:'',
            propertiesData:[],
            currentTaskMode:'',
            disabledTepBol:false,
            processNodeId:'',
            tempTaskBol:false,
            serintervalTimeFun:''
        }
    },
    props: ['projectId','sceneId','disabledAllBtn'],
    created(){
        // this.projectId = this.$route.query.projectId
        // this.sceneId = this.$route.query.sceneId || this.sceneId;
        // this.contentHeight = $(window).height() - 224
        // this.tableHeight = $(window).height() - 224 ;
        this.columnsData = [
            {
                type: 'selection',
                width: 60
                // align: 'center',
            },
            ...this.taskCol
        ];
        this.sceneId && this.getTaskList({
            "testId":this.sceneId,
			"pageIndex":this.taskCurrentPage,
            "pageSize":this.taskItemPage,
            "taskType":this.taskTypeTable,
            "taskMode":this.currentTaskMode,
        });
        // this.projectId = this.$route.params.username
    },
    beforeDestroy(){
        clearTimeout(this.serintervalTimeFun)
    },
    methods: {
        getMsgFormSon(data){
            this.propertiesData = data;
        },
        clickEvent: function(){
            // console.log('--')
            // console.log(this.headerData)
            // this.$emit("success",this.taskTypeTableTitle)
            // this.loadConfiguration(this.taskTypeTable)
            this.loadConfiguration("outband_capture")
        },
        handleSelectAll (status) {
            this.$refs.selection.selectAll(status)
        },
        autoConfigerTask(){
            axios({
                url:'pgconfig/task/edr/config',
                method:'POST',
                data:{
                    "projectId": this.projectId,
                    "testId": this.sceneId
                }
            }).then((response)=>{
                if (response.code==1) {
                    this.getTaskList({
                        "testId":this.sceneId,
                        "pageIndex":this.taskCurrentPage,
                        "pageSize":this.taskItemPage,
                        "taskType":this.taskTypeTable,
                        "taskMode":this.currentTaskMode,
                    });
                    this.$Message.success("配置成功")
                }else{
                    this.$Message.error(response.message);
                }
            })
        },
        createFlagTask(nodeId=''){
            this.tempTaskBol = false;
            this.formValidate.taskMode = "preset";
            this.$refs['formValidate'].resetFields();
            if(typeof(nodeId)=="string"){
                this.processNodeId = nodeId;
                if(nodeId=="temp"){
                    this.tempTaskBol = true
                    this.disabledTepBol = true;
                    this.formValidate.taskMode = 'temp'
                }
            }
            this.judgePanelType = true
            // this.$refs['formValidate'].resetFields();
            
            // this.$refs['formValidate'].resetFields();
            this.vmCurrentPage = 1
            this.vmItemPage = 10
            this.formValidate.configer = "";
            this.formValidate.subnets = "";
            this.formValidate.vmName = "";
            this.formValidate.vmIP = "";
            this.configurationData = [];
            this.$refs.store.clearSingleSelect()
            this.judgeVmStatus()
            // this.formValidate.taskMode = "preset";
            this.propertiesData = [{
                key:'',
                value:'',
            }];
            // this.loadConfiguration("outband_capture")
            this.getSubnetsOfProject({projectId:this.projectId,pageIndex:1,pageSize:10000})
            this.getVmList({page:this.vmCurrentPage,pageSize:this.vmItemPage,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
            this.createFlagTaskModal = true;
            // this.formValidate.name = "";
            
            this.formValidate.desc = ""
            // this.selectedVmDataTable = []
            this.selectedVmDataTable = []
            this.formValidate.selectedVmData = []
        },
        ok(){
            this.handleSubmit('formValidate')
        },
        cancel(){
            //  this.$Message.info('Clicked cancel')
        },
        handleSubmit (name) {
            let $this = this;
            this.properties = {};
            if(this.propertiesData.length!=0){
                let attrData = $this.propertiesData;
                for (let index = 0; index < attrData.length; index++) {
                    const element = attrData[index];
                    if(element.key){
                        $this.properties[element.key] = element.value;
                    }
                }
            }
            $this.$refs[name].validate((valid) => {
                if (valid) {
                    // $this.$Message.success('Success!');
                    if($this.selectedVmDataTable.length!=0){
                        if($this.judgePanelType){//判断是保存还是修改
                            $this.saveoutbandTask({
                                name:$this.formValidate.name,
                                

                                properties:$this.properties,
                                taskMode:$this.formValidate.taskMode,
                                description :$this.formValidate.desc,
                                deviceIdList :$this.formValidate.subnets,
                                deviceType:"SN",
                                taskType:$this.taskTypeTable,
                                testId:$this.sceneId,
                                metadata:{
                                    configId:$this.selectedVmDataTable[0],
                                    protocol:$this.formValidate.protocol,
                                }
                            })
                        }else{
                            $this.amendTask({
                                properties:$this.properties,
                                taskMode:$this.formValidate.taskMode,
                                name:$this.formValidate.name,
                                description :$this.formValidate.desc,
                                deviceIdList :$this.formValidate.subnets,
                                deviceType:"SN",
                                taskType:$this.taskTypeTable,
                                testId:$this.sceneId,
                                metadata:{
                                    configId:$this.selectedVmDataTable[0],
                                    protocol:$this.formValidate.protocol,
                                }
                            })
                        }
                    }else{
                        $this.$Message.info("请选择服务")
                        $this.createFlagTaskModalLoading = false;
                        $this.$nextTick(() => {
                            $this.createFlagTaskModalLoading = true;
                        });
                    }

                } else {
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                }
                
            });
        },
        handleReset (name) {
            this.$refs[name].resetFields();
        },
        addVmAfterTable(param){
            let data = this.dataVmList;
            this.dataVmList.forEach(function(item,i){
                if(item.id==param.row.id){
                    item._checked = true;
                    item._disabled = true;
                }
            })
        },
        handleAdd () {
            // if (this.selectedVmData.length) {
            //     this.selectedVmData.push(this.count[this.count.length - 1] + 1);
            // } else {
            //     this.selectedVmData.push(0);
            // }
        },
        handleClose2 (event, name) {
            // console.log(event)
            // console.log(name);
            let $this = this;
            let data = this.formValidate.selectedVmData;
            let _data = this.selectedVmDataTable;
            data.forEach(function(item,i){
                if(item){
                    if(item.id==name){
                        data.splice(i,1);
                        _data.remove(name);
                        $this.judgeVmStatus()
                    }
                }
            });
           
            // console.log(key);
            // const index = this.selectedVmData.indexOf(name);
            // this.count.splice(index, 1);
        },
        judgeVmStatus(){
            let data = this.dataVmList;
            let data_ = this.selectedVmDataTable
            // console.log(data_)
            data.forEach(function(item,i){
                // console.log(item.id)
                if(data_.indexOf(item.id)!=-1){
                    // alert('-')
                    item._checked = true;
                    item._disabled = true;
                }else{
                    item._checked = false;
                    item._disabled = false;
                }
            })
        },
        loadConfiguration(operation){
            let $this= this;
            axios({
                url:"tasktemplate/item",
                params:{
                    "operation":operation,
                    size: 2147483647
                },
            }).then((response)=>{
                $this.configurationData = [];
                if(response.code==1||response.code==0){
                    let ConfigurationList = response.data.list;
                    if(ConfigurationList==""){
                        return;
                    }
                    ConfigurationList.forEach(function(item,i) {
                        $this.configurationData.push({
                            name:item.name,
                            id:String(item.id),
                        })
                    });
                }else{
                    $this.$Message.error(response.message)
                }
            })
            // $.ajax({
            //     type:"get",
            //     url:_projPath_resTasktemplate +"item?"+GlobalTool.getParamStr({
            //         "operation":operation
            //     }),
            //     async:true,
            //     headers:{"Authorization":localStorage.token},
            //     dataType:"json",
            //     contentType:"application/json",
            //     success:function(reponse){
            //         $this.configurationData = [];
            //         if(reponse.code==1||reponse.code==0){
            //             let ConfigurationList = reponse.data.list;
            //             if(ConfigurationList==""){
            //                 return;
            //             }
            //             $.each(ConfigurationList, function(i,item) {
            //                 $this.configurationData.push({
            //                     name:item.name,
            //                     id:String(item.id),
            //                 })
            //             });
            //         }else{
            //             $this.$Message.error(reponse.message)
            //         }
            //     },
            //     error:function(){
            //         $this.$Message.error(errorMessage)
            //     }
            // });
        },
        getVmList(getParamObj){
            let $this = this;
            // $this.dataVmList = [];
            axios({
                url:"netns/config/servers?",
                params:getParamObj
            }).then((response)=>{
                if(response.code==1){
                    let result = response.attribute.dataList;
                    $this.vmTotal = Number(response.attribute.totalCount);
                    $this.dataVmList = result;
                }else{
                    $this.dataVmList = []
                }
            }).catch(error => {
                $this.dataVmList = []
            })
            // $.ajax({
            //     type:"get",
            //     url:_projPathNetns +"config/servers?"+GlobalTool.getParamStr(getParamObj),
            //     async:true,
            //     dataType:"json",
            //     contentType:"application/json",
            //     headers:{"Authorization":localStorage.token},
            //     success:function(reponse){
            //         if(reponse.code==1){
            //             let result = reponse.attribute.dataList;
            //             $this.vmTotal = Number(reponse.attribute.totalCount);
            //             $this.dataVmList = result;
            //         }else{

            //         }
            //     }
            // });



            return;

            $.ajax({
                type:"get",
                url: this.GLOBAL._projPath_deploy+'project/servers?'+this.BASE.getParamStr(getParamObj),
                async:true,
                contentType: 'application/json',
                dataType:'json',
                headers:{"Authorization":localStorage.token},
                success:function(data){
                    $this.dataVmList = [];
                    if(data.code==1){
                        let vmData = data.data.list;
                        $this.vmTotal = Number(data.data.count);
                        let disabled_ = false;
                        let checked_ = false;
                        vmData.forEach(function(item,i){
                            if($this.selectedVmDataTable.length!=0){
                                if($this.selectedVmDataTable.indexOf(item.id)!=-1){
                                    disabled_ = true
                                    checked_ = true
                                }else{
                                    disabled_ = false
                                    checked_ = false
                                }
                            }else{
                                disabled_ = false
                                checked_ = false
                            }
                            $this.dataVmList.push({
                                name:item.name,
                                id:item.id,
                                IP:item.addresses.map((item)=>item.ip),
                                _disabled: disabled_,
                                _checked:checked_,
                            })
                        })
                    }
                }
            });
        },
        switchineVmCurrentPage(numberPage){
            this.vmCurrentPage = numberPage;
            this.getVmList({page:this.vmCurrentPage,pageSize:this.vmItemPage,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
        },
        switchVmItemPage(numberSize){
            this.vmItemPage = numberSize
            this.getVmList({page:this.vmCurrentPage,pageSize:this.vmItemPage,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
        },
        saveoutbandTask(saveDateJson){
            let $this = this;
            axios({
                url:"process/tasks",
                method:'post',
                data:saveDateJson
            }).then((response)=>{
                if(response.code==1){
                    $this.createFlagTaskModal = false;
                    $this.$Message.success('添加任务成功');
                    this.taskCurrentPage = 1
                    this.taskItemPage = 10
                    $this.getTaskList({
                        "testId":$this.sceneId,
                        "pageIndex":$this.taskCurrentPage,
                        "pageSize":$this.taskItemPage,
                        "taskType":$this.taskTypeTable,
                        "taskMode":$this.currentTaskMode,
                    })
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                    if(typeof($this.processNodeId)=="string"){
                        if($this.tempTaskBol){
                            axios({
                                url:"process/tasks/"+response.data.id+'/execute?operation=start',
                                method:'post'
                            }).then((data)=>{
                                let activeType;
                                if(data.code==1){
                                    $this.$Message.success("启动任务成功")
                                }else{
                                    $this.$Message.error(response.message)
                                }
                            })
                        }else{
                            axios({
                                url:'process/tasks/'+response.data.id+'?nodeId='+$this.processNodeId,
                                method:'patch'
                            }).then((data)=>{
                                if (data.code==1) {
                                    $this.processNodeId = "";
                                } else {
                                    $this.$Message.error(data.message)
                                }
                            })
                        }
                    }else{
                        $this.$parent.getStatisticsList();
                    }
                }else{
                    $this.$Message.error(response.message)
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                }
            })
        },
        getTaskList(obj){
            this.selectedData = [];
            let $this = this;
            clearTimeout($this.serintervalTimeFun)
            axios({
                url:"process/tasks",
                params:obj,
                method:'get'
            }).then((response)=>{
                if(response.code==1){
                    $this.taskData = [];
                    $this.taskTotal = response.data.total;
                    let setintrvalBol = false
                    // let _s = 0,_e = 0,_i = 0,_r = 0,stintervalBol = false;
                    if(response.data.items.length!=0){
                        // $this.taskData = reponse.data.list;
                        $this.taskData = response.data.items.map((item)=>{
                            if($this.selectedData.map((item)=>item.id).join(',').indexOf(item.id)!=-1){
                                item['_checked'] = true;
                            }else{
                                item['_checked'] = false;
                            }
                            return item;
                        });
                        response.data.items.forEach(function(item,i){
                            if(item.status=="running"||item.status=="starting"||item.status=="closing"){
                                // _r++;
                                setintrvalBol = true;
                            }
                        })
                    }
                    if(setintrvalBol){
                        // $this.headerData.serintervalTimeFun  = setInterval( $this.setintervalTaskList, 2000);
                        $this.serintervalTimeFun  = setTimeout(() => {
                            $this.getTaskList({
                                "testId":$this.sceneId,
                                "pageIndex":$this.taskCurrentPage,
                                "pageSize":$this.taskItemPage,
                                "taskType":$this.taskTypeTable,
                                "taskMode":$this.currentTaskMode,
                            })
                        }, 5000);
                    }else{
                        clearTimeout($this.serintervalTimeFun)
                        // $this.getTaskList({
                        //     "testId":this.projectId,
                        //     "page":this.taskCurrentPage,
                        //     "rows":this.taskItemPage,
                        //     "taskType":"",
                        //     "node":"false",
                        // })
                    }
                    // $this.getTaskListDeailData()
                    // $this.$emit("success",$this.taskTypeTableTitle+'-'+_s+'-'+_e+'-'+_i+'-'+_r+'-'+stintervalBol+'-'+$this.taskCurrentPage+'-'+$this.taskItemPage)
                }else if(response.code==-2){
                    
                }else{
                    $this.$Message.error(response.message)
                }
            })
            
        },
        switchineTaskCurrentPage(numberPage){
            this.taskCurrentPage = numberPage;
            this.getTaskList({
                "testId":this.sceneId,
                "pageIndex":this.taskCurrentPage,
                "pageSize":this.taskItemPage,
                // "configType":"",
                "taskType":this.taskTypeTable,
                "taskMode":this.currentTaskMode,
            })
        },
        switchTaskItemPage(numberSize){
            this.taskItemPage = numberSize
            this.getTaskList({
                "testId":this.sceneId,
                "pageIndex":this.taskCurrentPage,
                "pageSize":this.taskItemPage,
                // "configType":"",
                "taskType":this.taskTypeTable,
                "taskMode":this.currentTaskMode,
            })
        },
        deleteTask(taskId,task){
            let $this = this
            axios({
                url:"process/tasks/"+taskId,
                method:'delete'
            }).then((response)=>{
                if(response.code==1){
                    if(response.data[0].code==1){
                        $this.taskCurrentPage = ($this.taskData.length == 1 && $this.taskCurrentPage > 1) ?
                            $this.taskCurrentPage -1 : $this.taskCurrentPage;
                        $this.getTaskList({
                            "testId":$this.sceneId,
                            "pageIndex":$this.taskCurrentPage,
                            "pageSize":$this.taskItemPage,
                            "taskType":$this.taskTypeTable,
                            "taskMode":$this.currentTaskMode,
                        })
                        this.selectedData.splice(this.taskData.findIndex(task => task.id === taskId),1);
                        $this.$Message.success("删除成功")
                        // $this.$parent.getStatisticsList();
                    }else{
                        $this.$Message.error(response.data[0].message)
                    }
                }else{
                    $this.$Message.error(response.data[0].message)
                }
            })
            
        },
        updateTask(taskId){
            this.judgePanelType = false
            this.formValidate.vmName = "";
            this.formValidate.vmIP = "";
            let $this = this
            axios({
                url:"process/tasks/"+taskId,
            }).then((response)=>{
                if(response.code==1){
                    $this.queryServerDeail(response.data.metadata.configId)
                    $this.workingAreaTaskId = response.data.id
                    $this.formValidate.selectedVmData = []
                    $this.formValidate.subnets = []
                    $this.propertiesData = [];
                    $this.createFlagTaskModal = true;
                    $this.formValidate.name = response.data.name;
                    $this.formValidate.desc = response.data.description;
                    $this.formValidate.protocol = response.data.metadata.protocol
                    // $this.formValidate.configer = reponse.data.configId;
                    if(response.data.deviceData.length!=0){
                        response.data.deviceData.forEach(function(item,i){
                            // $this.selectedVmDataTable.push(item.deviceId);
                            $this.formValidate.subnets.push(item.deviceId)
                        })
                    }
                    $this.formValidate.taskMode = response.data.taskMode;
                    if(JSON.stringify(response.data.properties)!="{}"){
                        for(let i in response.data.properties){
                            let obj = {};
                            obj['key'] = i;
                            obj['value'] = response.data.properties[i];
                            $this.propertiesData.push(obj)
                        }
                    }
                    console.log($this.formValidate.selectedVmData)
                }else{
                    $this.workingAreaTaskId = ""//清空任务id
                    $this.$Message.error(response.message)
                }
            }).then(()=>{
                this.getSubnetsOfProject({projectId:this.projectId,page:1,rows:10000})
                $this.getVmList({page:this.vmCurrentPage,pageSize:this.vmItemPage,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
                $this.judgeVmStatus()
            })
            this.getSubnetsOfProject({projectId:this.projectId,page:1,rows:10000})
            $this.getVmList({page:this.vmCurrentPage,pageSize:this.vmItemPage,order:"asc",sortBy:"name",name:this.formValidate.vmName,ip:this.formValidate.vmIP})
            $this.judgeVmStatus()
        },
        async queryServerDeail(configId){
            let $this = this;
            await axios({
                url:"netns/config/server/"+configId,
            }).then((response)=>{
                $this.selectedVmDataTable = []
                if(response.code==1){
                    $this.configName = response.attribute.result.name;
                    $this.selectedVmDataTable.push(configId)
                    $this.formValidate.selectedVmData.push({
                        name:$this.configName,
                        id:configId
                    })
                }else  if(response.code == -2){
                    $this.formValidate.selectedVmData.push({
                        name:"--",
                        id:response.data.metadata.configId
                    })
                }else{
                     $this.$Message.error(response.message)
                }
            })
            // $.ajax({
            //     type:"get",
            //     url:"netns/config/server/"+configId,
            //     async:false,
            //     dataType:"json",
            //     // data:JSON.stringify(amendTaskData),
            //     headers:{"Authorization":localStorage.token},
            //     contentType:"application/json",
            //     // error:function(){
            //     //     $this.$Message.error(errorMessage)
            //     // },
            //     success:function(reponse){
            //         if(reponse.code==1){
            //             $this.configName = reponse.attribute.result.name
            //         }else{
            //             $this.configName = '--'
            //            $this.$Message.error(reponse.message)
            //         }
            //     },
            // });
            // return configName;
        },
        amendTask(amendTaskData){
            let $this = this;
            axios({
                url:"process/tasks/"+this.workingAreaTaskId,
                method:'put',
                data:amendTaskData
            }).then((response)=>{
                if(response.code==1){
                    $this.createFlagTaskModal = false;
                    $this.$Message.success("修改成功");
                    $this.getTaskList({
                        "testId":$this.sceneId,
                        "pageIndex":$this.taskCurrentPage,
                        "pageSize":$this.taskItemPage,
                        "taskType":$this.taskTypeTable,
                        "taskMode":$this.currentTaskMode,
                    })
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                }else{
                    $this.$Message.error(response.message)
                    $this.createFlagTaskModalLoading = false;
                    $this.$nextTick(() => {
                        $this.createFlagTaskModalLoading = true;
                    });
                }
            })
        },
        activeTask(taskId,active){
            console.log(active,'状态输出')
            let $this = this
            let op;
            if(active=="开始"){
                op = "start"
            }else if(active=="停止"){
                op = "stop"
            }
            axios({
                url:"process/tasks/"+taskId+'/execute?operation='+op,
                method:'post'
            }).then((response)=>{
                let activeType;
                if(response.code==1){
                    $this.$Message.success(active+"任务成功")
                    $this.getTaskList({
                        "testId":$this.sceneId,
                        "pageIndex":$this.taskCurrentPage,
                        "pageSize":$this.taskItemPage,
                        "taskType":$this.taskTypeTable,
                        "taskMode":$this.currentTaskMode,
                    });
                }else{
                    $this.$Message.error(response.message)
                }
            })
        },
        taskDeail(taskId,text){
            let $this = this
            axios({
                url:"process/tasks/"+taskId+'/histories',
            }).then((response)=>{
                if(response.code==1){
                    $this.taskDeailData = [];
                    $this.taskDeailModal = true
                    // $this.taskDeailData= reponse.data;
                    response.data.forEach(function(item,i){
                        $this.taskDeailData.push({
                            deviceName:item.deviceName,
                            status:item.status,
                            message:item.message,
                            deviceId:item.deviceId,
                            host:'',
                            hostIp:'',
                            instance:'',
                            osId:'',
                            created:item.created ? item.created:'',
                            updated:item.updated ? item.updated:'',
                            _expanded:false,
                            protocol:text
                        })
                    })
                }else{
                    $this.$Message.error(response.message)
                }
            })
        },
        deleteManyTask(selection){
            let $this = this;
            if(this.selectedData.length==0){
                this.$Message.error("请选择要删除的任务")
            }else{
                axios({
                    url:"process/tasks/"+this.selectedData.map((item)=>item.id).join(','),
                    method:'delete'
                }).then((response)=>{
                    if(response.code==1){
                        response.data.forEach(function(item,i){
                            if(item.code==1){
                                $this.taskCurrentPage = ($this.taskData.length == $this.selectedData.length && $this.taskCurrentPage > 1) ?
                                    $this.taskCurrentPage -1 : $this.taskCurrentPage;
                                $this.$Message.success("删除成功")
                            }else{
                                $this.$Message.error(item.message)
                            }
                        })
                        this.selectedData = [];
                        $this.getTaskList({
                            "testId":$this.sceneId,
                            "pageIndex":$this.taskCurrentPage,
                            "pageSize":$this.taskItemPage,
                            "taskType":$this.taskTypeTable,
                            "taskMode":$this.currentTaskMode,
                        })
                    }else{
                        $this.$Message.error(response.message)
                    }
                })
            }
        },
        getSelectedTableItem(selection){
            this.selectedData = [];
            this.selectedData = selection
            
            console.log(selection)
        },
        hostDeail(row){
            console.log(row.deviceId);
            let $this  = this;
            if(!row._expanded){
                axios({
                    url:"deploy/project/servers/"+row.deviceId,
                }).then((response)=>{
                    if(response.code==1){
                        $this.taskDeailData.forEach(function(item,i){
                            if(row.deviceId==item.deviceId){
                                item._expanded = true
                                item.host = response.data.host;
                                item.hostIp = response.data.hostIp;
                                item.instance = response.data.instance;
                                item.osId= response.data.osId;
                                // item.created = reponse.data.created ? reponse.data.created : ''
                                // item.updated = reponse.data.updated ? reponse.data.updated : ''
                                return false;
                            }
                        })
                    }
                })
            }else{
                row._expanded = !row._expanded;
            }
        },
        // setintervalTaskList(obj){
        //     let $this = this;
        //     $.ajax({
        //         type:"get",
        //         url:_projPath_process +"tasks?"+GlobalTool.getParamStr(obj),
        //         async:true,
        //         dataType:"json",
        //         headers:{"Authorization":localStorage.token},
        //         contentType:"application/json",
        //         success:function(reponse){
        //             if(reponse.code==1){
        //                 if(reponse.data.list.length!=0){
        //                     $.each(reponse.data.list,function(i,item){

        //                     })
        //                     $this.taskData = reponse.data.list;
        //                 }
        //             }else if(reponse.code==-2){
                        
        //             }else{
        //                 $this.$Message.error(response.message)
        //             }
        //         },
        //         error:function(){
        //             $this.$Message.error(errorMessage)
        //         }
        //     });
        // },
        refreshTaskList(){
            this.getTaskList({
                "testId":this.sceneId,
                "pageIndex":this.taskCurrentPage,
                "pageSize":this.taskItemPage,
                "taskType":"",
                "taskMode":this.currentTaskMode,
            });
        },
        refreshVmList(){
            this.vmCurrentPage = 1;
            this.getVmList({
                page:this.vmCurrentPage,
                pageSize:this.vmItemPage,
                order:"asc",
                sortBy:"name",
                name:this.formValidate.vmName,
                ip:this.formValidate.vmIP
            })
        },
        getTaskListDeailData(){
            let $this = this
            axios({
                url:"process/overview/task/countByStatus",
                params:{
                    "testId":$this.sceneId,
                    "taskType":$this.taskTypeTable,
                    "node":"false"
                },
            }).then((response)=>{
                if(response.code==1){
                    let _s = 0,_e = 0,_i = 0,_r = 0,stintervalBol = false;
                    _s = response.data.completed;
                    _e = response.data.error;
                    _i = response.data.initialized;
                    _r = Number(response.data.running)+Number(response.data.starting)+Number(response.data.closing);
                    if(_r!=0){
                        stintervalBol = true;
                    }
                    $this.$emit("success",$this.taskTypeTableTitle+'-'+_s+'-'+_e+'-'+_i+'-'+_r+'-'+stintervalBol+'-'+$this.taskCurrentPage+'-'+$this.taskItemPage)
                }else if(response.code==-2){
                    
                }else{
                    $this.$Message.error(response.message)
                }
            })
            
        },
        setintervalTaskList(){
            // alert('-')
            let $this = this;
            axios({
                url:"process/tasks",
                method:'get',
                params:{
                    "testId":this.sceneId,
                    "pageIndex":this.taskCurrentPage,
                    "pageSize":this.taskItemPage,
                    "taskType":this.taskTypeTable,
                    // "node":"false"
                },
            }).then((response)=>{
                if(response.code==1){
                    $this.taskData = [];
                    if(response.data.items.length!=0){
                        let stintervalBol  = false
                        $this.taskData = response.data.items
                        response.data.items.forEach(function(item,i){
                            if(item.status=="running"||item.status=="starting"||item.status=="closing"){
                                stintervalBol = true
                            }
                            $this.taskData[i].status = item.status;
                        })
                        if(!stintervalBol){
                            clearInterval($this.serintervalTimeFun)
                        }
                    }
                    $this.getTaskListDeailData()
                }else if(response.code==-2){
                    
                }else{
                    $this.$Message.error(response.message)
                }
            })
            
        },
        getSubnetsOfProject(obj){
            let _this = this
            axios({
                url:"topo-edit/deployed/projects/"+this.projectId+"/subnets",
                params:obj,
                method:'get'
            }).then((response)=>{
                if(response.code==1){
                     _this.subnetsData = []
                    _this.subnetsData = response.data.items
                }else{
                    _this.$Message.error(response.message)
                }
            })
        }
    },
    watch:{
        sceneId(){
            this.getTaskList({
                "testId":this.sceneId,
                "pageIndex":this.taskCurrentPage,
                "pageSize":this.taskItemPage,
                "taskType":this.taskTypeTable,
                "taskMode":this.currentTaskMode,
            });
        }
    }
}
</script>


